package com.peaksport.framework.base.service;

import java.util.ArrayList;
import java.util.List;

import com.peaksport.framework.base.entity.BillBaseEntity;
import com.peaksport.framework.base.entity.EntryBaseEntity;
import com.peaksport.framework.base.entity.IEntityObject;
import com.peaksport.framework.exception.PKDevException;
import com.peaksport.framework.util.PKPublicUtils;

public abstract class BillBaseService extends ObjectBaseService {

	@Override
	public IEntityObject save(IEntityObject entity) {
		if (!(entity instanceof BillBaseEntity))
			throw PKDevException.throwException("entity实体[%s]不是[%s]基类,请开发人员检查.",entity.getClass(),BillBaseEntity.class.getName());
		BillBaseEntity billBaseEntity = (BillBaseEntity)entity;
		List<?> lstEntrys = billBaseEntity.getEntrys();
		if (lstEntrys == null) lstEntrys = new ArrayList<>();
		boolean isNew = PKPublicUtils.isEmpty(billBaseEntity.getId());
		int seqIndex = 0;
		//当更新保存数据时,先获取最大序号,再往下编码
		for (int i = 0,len=lstEntrys.size(); !isNew && i < len; i++) {
			Object entry = lstEntrys.get(i);
			if (!(entry instanceof EntryBaseEntity))
				throw PKDevException.throwException("分录实体[%s]不是[%s]基类,请开发人员检查.",entry.getClass(),EntryBaseEntity.class.getName());
			EntryBaseEntity entryBaseEntry = (EntryBaseEntity)entry;
			int curSeqIndex = entryBaseEntry.getSeq();
			if (curSeqIndex > seqIndex) seqIndex = curSeqIndex;
		}
		for (int i = 0, len = lstEntrys.size(); i < len; i ++) {
				Object entry = lstEntrys.get(i);
				if (!(entry instanceof EntryBaseEntity))
					throw PKDevException.throwException("分录实体[%s]不是[%s]基类,请开发人员检查.",entry.getClass(),EntryBaseEntity.class.getName());
				EntryBaseEntity entryBaseEntry = (EntryBaseEntity)entry;
				if (entryBaseEntry.getSeq() > 0) continue;
				seqIndex++;
				entryBaseEntry.setSeq(seqIndex);
		}
		
		return super.save(entity);
	}
	
	/*public IEntityObject audit(Class<?> entityClass, String pk) {
		if (PKClassUtils.isAssignableFrom(BillBaseEntity.class, entityClass))
			throw PKDevException.throwException("entity实体[%s]不是[%s]基类,请开发人员检查.",entityClass.getName(),BillBaseEntity.class.getName());
		String tableName = PKClassUtils.getTableName(entityClass);
		Method method = PKClassUtils.getMethod(entityClass, "getEntrys", null);
		Class<?> entryEntityClass = PKClassUtils.getMethodGenericReturnType(method);
		String entryTableName = PKClassUtils.getTableName(entryEntityClass);
		ContextInfo contextInfo = getContextInfo();
		Date now = getCurrentDate();
	
		UserEntity userEntity = contextInfo.getUserEntity();
		billBaseEntity.setAuditor(userEntity);
		billBaseEntity.setAuditTime(now);
		billBaseEntity.setBaseStatus(BillBaseStatusEnum.AUDITED);
		
		return billBaseEntity;
	}*/
}
